/**
 * org.assess.core.common.ByteUtils
 */
package org.assess.core.common;

import java.util.Arrays;

/**
 * @description Byte工具
 * @author XiaLongxiang
 * @createtime 2012-2-10 下午5:03:56
 */
public class ByteUtils {
    /**
     * 将16进制的字符串转换成16进制的数组
     * @param str
     * @return
     */
    public static byte[] parse16(String str) {
        // 如果传入的字符串不为空且包含除空白字符外的其他字符，则进行转换，反之则返回null
        if (org.apache.commons.lang.xwork.StringUtils.isNotBlank(str)) {
            int count = 0;
            byte[] bytes = new byte[str.length()];
            char[] chars = str.toCharArray();
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                if (Character.isWhitespace(chars[i])) {
                    index = i + 1;
                }
                else if (index != i) {
                    bytes[count++] = (byte) Integer.parseInt(new String(new char[] {chars[index], chars[i]}), 16);
                    index = i + 1;
                }
            }
            
            return Arrays.copyOf(bytes, count);
        }
        else {
            return null;
        }
    }
    
    /**
     * 将16进制的字符串转换成16进制的数组，返回的数组具有指定长度
     * @param str
     * @param length
     * @return
     */
    public static byte[] parse16(String str, int length) {
        byte[] bytes = parse16(str);
        byte[] results = new byte[length];
        if (bytes.length <= length) {
            System.arraycopy(bytes, 0, results, length - bytes.length, bytes.length);
        }
        else if (bytes.length > length) {
            System.arraycopy(bytes, bytes.length - length, results, 0, length);
        }
        return results;
    }
    
    /**
     * 将指定的数据转换成byte数组
     * @param number
     * @return
     */
    public static byte[] parse16(long num, int length) {
        byte[] results = new byte[length];
        for (int i = length - 1; i >= 0; i--) {
            results[length - 1 - i] = (byte) (num >>> (i * 8) & 0xff);
        }
        
        return results;
    }
    
    public static void main(String[] args) {
        
    }
}
